﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using PMS.Win;
using PMS.Utils;
using System.Data.SqlClient;
using PMS.Resources;

namespace Configuration
{
    public partial class Config : FormManualBase
    {
        ConfigEngine cf = new ConfigEngine();
        public Config()
        {
            InitializeComponent();
            loadonform();
        }

        private void btnSave_Click(object sender, EventArgs e)
        {
            try
            {
                Dictionary<string,string> dic = GetConnecting();
                if (testConnecting(dic))
                {
                    cf.WriteConnectingString(dic);
                    ShowSaveSuccedMessage();
                }
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
            }
        }

        private void btnTest_Click(object sender, EventArgs e)
        {
            if (testConnecting(GetConnecting()))
            {
                btnSave.Enabled = true;
                MessageBox.Show(Messages.GetString("TestConnectSuccessful"));
            }
            else
            {
                ShowErrorMessage(Messages.GetString("TestConnectingFail"));
            }
        }

        private void loadonform()
        {
            Dictionary<string, string> dic = cf.ReadConnectingString();
            if (dic.ContainsKey("Data Source")) txtServer.Text = dic["Data Source"];
            if (dic.ContainsKey("Initial Catalog")) txtDatabase.Text = dic["Initial Catalog"];
            if (dic.ContainsKey("User Id")) txtUser.Text = dic["User Id"];
            if (dic.ContainsKey("Password")) txtPassword.Text = dic["Password"];

        }

        private Dictionary<string, string> GetConnecting()
        {
            Dictionary<string, string> dic = new Dictionary<string, string>();

            dic.Add("Data Source", DataConvertUltils.ToString(txtServer.EditValue));
            dic.Add("Initial Catalog", DataConvertUltils.ToString(txtDatabase.EditValue));
            dic.Add("User Id", DataConvertUltils.ToString(txtUser.EditValue));
            dic.Add("Password", DataConvertUltils.ToString(txtPassword.EditValue));

            return dic;
        }

        private bool testConnecting(Dictionary<string, string> dic)
        {
            try
            {
                string connecting = cf.Connectingstring(dic);
                SqlConnection con = new SqlConnection(connecting);
                con.Open();
                con.Close();
                return true;
            }
            catch (Exception ex)
            {
                ShowErrorMessage(ex);
                return false;
            }
        }
    }
}
